'use strict';

export default function (Vue, config) {
  /**
   * {
   *   "host?": "http://localhost:7011",
   *   "prefix?": "lib",
   *   "repo": "user/repo",
   *   "type": "lib | wc | wc-async",
   *   "version?": "latest",
   *   "min?": 1,
   *   "sig?": 0,
   *   "schema?": "default",
   *   "url?": "http://example.com/lib.js"
   * }
   *
   * if set url argument, `host` `prefix` `version` `min` `sig` will not use.
   *    but `repo` `type` `schema` is required
   *
   */
  return function (modules) {
    const all = [];
    for (const module of modules) {
      const _type = (module.type || 'lib').toLowerCase();
      if (!module.repo) {
        console.error('lose lib repo');
        continue;
      }
      const six = module.repo.indexOf('/');
      const _name = module.repo.substring(six < 0 ? 0 : six + 1);
      if (_type === 'lib' && window[_name]) {
        console.warn(module.repo, 'Already loaded');
        continue;
      }
      const host = module.host || config.host;
      const prefix = module.prefix || config.prefix || 'lib';
      // const suffix = module.suffix || config.suffix || (_type === 'lib' ? '.umd.min.js' : '.min.js');
      // const url = `${host || ''}${module.path || ''}/${_name}/${_name}${suffix}`;
      let url;
      if (module.url) {
        url = module.url;
      } else {
        url = (host || '') + (host.endsWith('/') ? '' : '/') +
          (prefix ? prefix + '/' : '') +
          module.repo + '/' +
          (module.version || 'latest') + '?' +
          'type=' + (_type ? (_type === 'lib' ? 'umd' : _type) : 'umd') +
          (module.min ? '&min=1' : '') +
          (module.sig ? '&sig=1' : '')
      }
      const promise = new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.onload = () => {
          if (_type === 'lib') {
            if (window[_name]) {
              // console.log("typeof window[_name] === 'function'", typeof window[_name] === 'function');
              // console.log("typeof window[_name] === 'function'", this);
              typeof window[_name] === 'function'
                ? window[_name].call(window['_vue'], Vue)
                : window[_name][module.schema || 'default'].call(window['_vue'], Vue);
              console.log(
                `%c${module.repo}%cLoad success`,
                'background: #00d1b2; padding: 5px; color: #fff; border-radius: 5px 0 0 5px',
                'background: #555; padding: 5px; color: #fff; border-radius: 0 5px 5px 0'
              );
            } else {
              console.warn(module.repo, ': Load lib fail. the script is not a vue lib.')
            }
          } else {
            console.log(
              `%c${module.repo}%cLoad success`,
              'background: #c100d1; padding: 5px; color: #fff; border-radius: 5px 0 0 5px',
              'background: #555; padding: 5px; color: #fff; border-radius: 0 5px 5px 0'
            );
          }
          resolve();
        };
        script.onerror = () => {
          console.warn(module.repo, `: Load ${_type} fail. can not load url: ${url}`);
          resolve();
        };
        document.body.appendChild(script)
      });
      all.push(promise);
    }
    return Promise.all(all);
  }
}

